% Save Images as Dicom files;
function patient = save_4DCT_as_DICOM_toolbox(patient)
    %| Save the model derived 4DCT scans as DICOM, using the annonamized
    %|patient DICOM tags as the dicom info, and writing using Matlab's
    %|dicomwrite.
    %------------------------------------------------------------------------
    %|      Dependancies;
    %|
    %|
    %------------------------------------------------------------------------
    %   This file is part of the
    %   5D-Novel4DCT Toolbox  ("Novel4DCT-Toolbox")
    %   DH Thomas, Ph.D
    %   University of California, Los Angeles
    %   Contact: mailto:dhthomas@mednet.ucla.edu
    %------------------------------------------------------------------------
    % $Author: DHThomas $	$Date: 21-May-2014 16-24-20 $	$Revision: 0.1 $
    
    cd(patient.folder_static)
    cd ..
    patient.folder_original_dicoms = pwd;
    directory_tmp=dir;
    
    isub = [directory_tmp(:).isdir]; %# returns logical vector
    nameFolds = {directory_tmp(isub).name}';
    temp_dir=dir('*sync*');
    
    nameFolds(ismember(nameFolds,{'.','..',temp_dir.name})) = [];
    if size(nameFolds,1)<patient.scans
        error('myApp:folderChk', 'Less DICOM folders exist than scan numbers requested')
    end
    
    dir_sort_prep={nameFolds};
    for i=1: length(dir_sort_prep{:});
        temp_list(i)=str2num(cell2mat((dir_sort_prep{:}(i))));
    end
    sort_folder=(sort(temp_list))';%num2str
    
    dicom_original_folder=num2str(sort_folder(1));
    cd(num2str(sort_folder(1)))
    temp_dir=[dir('*dcm*');dir('*ima*')];
    if size(temp_dir,1)<patient.dim(3)
        error('myApp:folderChk', 'Less DICOM slices exist requested')
    end
    
    phases=[1:patient.num_phases_4dct];%[5:10:85]
    dicom_info_folder = [1:length(phases)];% choose original scans to grab dicom info from
    
    folder_dicom = [patient.model_folder '\Psuedo_4DCT_DICOM'];
    folder_images = [patient.model_folder '\Psuedo_4DCT'];
    mkdir(folder_dicom)
    
    phases=[1:8];%[5:10:85]
    description_phases = [0    25    50    75   100    75    50    25];
    inex = ['Ex'; 'In' ;'In' ;'In' ;'Ex';'Ex' ;'Ex' ;'Ex']

    
    for phase=1:size(phases,2)
        display(sprintf('Creating DICOMs, phases %d of %d',phase,size(phases,2)));
        %cd(folder_images)
        scan_folder = [folder_images];% sprintf('\\scan%d',phase)]
        deformed_image = metaImageRead([scan_folder sprintf('\\Deformed_pseudo_Image_phase_%d', phase)]);
        %     img=load(sprintf('Deformed_pseudo_Image_phase_%d',phases(phase)));
        %     img_tmp=img.deformed_image;
        
        cd([patient.folder_original_dicoms '/' num2str(sort_folder(dicom_info_folder(phase)))]);
        temp_dir=dir('*');;%temp_dir(1:2)=[];
        temp_dir(1:2) = []
        
        s=temp_dir(1).name;
        info=dicominfo(s);
        
        info=dicominfo(s);
        slice_thickness=info.SliceThickness;
        pixel_size=info.PixelSpacing;
        resolution(1) = info.Rows;
        resolution(2) = info.Columns;
        if info.Width>patient.dim(1);
        img=resample3Dimage_3factors(deformed_image,pixel_size(1),pixel_size(2),slice_thickness);
        %img(:,:,end+1) = img(:,:,end);
        else
            img = deformed_image;
        end
        clear deformed_image
        dim = size(img);
        
        img_full = info.RescaleIntercept*ones([resolution dim(3)]);
        aa = 1+(resolution(1)-dim(1))/2:(resolution(1)-dim(1))/2+dim(1);
        bb = 1+(resolution(2)-dim(2))/2:(resolution(2)-dim(2))/2+dim(2);
        img_full(aa,bb,:) = img;
        %     img = flipdim(img_full,3);
        img = img_full;
        %re-orientate (?) the images with the original DICOMS;
        if patient.directions(phase) == 0;
            img = flipdim(img_full,3);
        end
        
        %         mask=load(sprintf('Deformed_pseudo_Mask_phase_%d',phases(phase)));mask=mask.deformed_mask;

        img_dcm = round(img - info.RescaleIntercept*info.RescaleSlope);
%                if phase<6;
            output_phase=[folder_dicom sprintf('\\phase_%02d %s',  phases(phase),inex(phase,:))];
%         else
%             output_phase=[folder_dicom sprintf('\\phase_%02d Ex',phases(phase))];
%         end
% output_phase=[folder_dicom sprintf('\\phase_%02d',phases(phase))];
        
%         cd(folder_dicom)
        mkdir(output_phase);
        
        if patient.par_toolbox>0;
            
            pctRunOnAll javaaddpath E:\ParforProgMonv2\java
            progressStepSize = 1;
            ppm = ParforProgMon('                        Lung: ',dim(3),  progressStepSize,1000, 100);
            tic
            clear infos acq_time
            for slice = 1:length(temp_dir);
                infos = dicominfo(temp_dir(slice).name);
                acq_time(:,slice) = str2num(infos.AcquisitionTime);
            end
            [c slice_order] = sort(acq_time);
            for slice=1:dim(3);%:-1:1;
                %             cd(folder_static);
                %             cd ..;
                dicom_folder_tmp = fullfile(patient.folder_original_dicoms , num2str(sort_folder(dicom_info_folder(phase))));
                %             cd([patient.folder_original_dicoms '/' num2str(sort_folder(dicom_info_folder(phase)))])
                s=temp_dir(slice_order(slice)).name;
                dicom_filename_tmp = fullfile(dicom_folder_tmp, s);
%                 dicom_filename_tmp2 = [dicom_filename_tmp(1:end-4) '_tmp.dcm'];
%                 dicomanon(dicom_filename_tmp, dicom_filename_tmp2) % temporarily anonamize the raw dicom info
                info=dicominfo(dicom_filename_tmp);
%                 delete(dicom_filename_tmp2); % delete the temp dicom
                %clean up the dicom info (just in case);
                info.PatientAddress ='';
                info.PatientAge = '';
                info.PatientBirthDate = '';
                info.RequestingPhysician = '';
                info.PatientName = '';
                info.PatientID = num2str(patient.pt);
                info.Patient = num2str(patient.pt);
                
                %Rename the DICOMs (patient name);
                info.PatientName = sprintf('5DResearch Patient %d',patient.pt);
                info.SeriesNumber = phase;
%                 if phase<6;
                    if patient.use_average_image ==0
                    info.SeriesDescription = sprintf('%d%% %s ',description_phases(phase), inex(phase,:));
                    else
                    info.SeriesDescription = sprintf('%d%% %s - averaged reference',description_phases(phase), inex(phase,:));
                    end
                    info.SeriesInstanceUID = [num2str(patient.pt) '.' num2str(phase)];%'85';
                    info.StudyInstanceUID = num2str(patient.pt);%'85';
                    info.StudyID = num2str(patient.pt);

%                 else
%                     if patient.use_average_image ==0
%                     info.SeriesDescription = sprintf('%d%% In ',description_phases(phase));
%                     else
%                     info.SeriesDescription = sprintf('%d%% In - averaged reference',description_phases(phase));
%                     end
%                     info.SeriesInstanceUID = [num2str(patient.pt) '.' num2str(phase)];%'85';
%                     info.StudyInstanceUID = num2str(patient.pt);%'85';
%                     info.StudyID = num2str(patient.pt);
%                 end                %         X=dicomread(s);
                %         cd(folder_output)
                %         cd(dicom_folder)
                %             cd(output_phase)
                %         dicomwrite(double(squeeze(X(:,:))),map,sprintf('image_phase_5_slice%d.dcm',slice),  info);
                output_file_tmp = fullfile(output_phase,sprintf('image_Phase_%02d_slice%d.dcm',phases(phase),slice) );
                dicomwrite(uint16(double(squeeze(img_dcm(:,:,slice)))),output_file_tmp,  info, 'CreateMode', 'Copy');
                
                ppm.increment();
                
            end
            ppm.delete()
        else
            for slice=1:dim(3);%:-1:1;
                %             cd(folder_static);
                %             cd ..;
                dicom_folder_tmp = fullfile(patient.folder_original_dicoms , num2str(sort_folder(dicom_info_folder(phase))));
                %             cd([patient.folder_original_dicoms '/' num2str(sort_folder(dicom_info_folder(phase)))])
                s=temp_dir(slice_order(slice)).name;
                dicom_filename_tmp = fullfile(dicom_folder_tmp, s);
%                 dicom_filename_tmp2 = [dicom_filename_tmp(1:end-4) '_tmp.dcm'];
%                 dicomanon(dicom_filename_tmp, dicom_filename_tmp2)
                info=dicominfo(dicom_filename_tmp);
%                 delete(dicom_filename_tmp2)
                info.PatientAddress ='';
                info.PatientAge = '';
                info.PatientBirthDate = '';
                info.RequestingPhysician = '';
                info.PatientName = '';
                info.PatientID = num2str(patient.pt);
                info.Patient = num2str(patient.pt);
                                %Rename the DICOMs (patient name);
                info.PatientName = sprintf('5DResearch Patient %d',patient.pt);
                info.SeriesNumber = phase;
                if phase<6;
                    if patient.use_average_image ==0
                    info.SeriesDescription = sprintf('%d%% In ',description_phases(phase));
                    else
                    info.SeriesDescription = sprintf('%d%% In - averaged reference',description_phases(phase));
                    end
                    info.SeriesInstanceUID = [num2str(patient.pt) '.' num2str(phase)];%'85';
                    info.StudyInstanceUID = num2str(patient.pt);%'85';
                    info.StudyID = num2str(patient.pt);

                else
                    if patient.use_average_image ==0
                    info.SeriesDescription = sprintf('%d%% In ',description_phases(phase));
                    else
                    info.SeriesDescription = sprintf('%d%% In - averaged reference',description_phases(phase));
                    end
                    info.SeriesInstanceUID = [num2str(patient.pt) '.' num2str(phase)];%'85';
                    info.StudyInstanceUID = num2str(patient.pt);%'85';
                    info.StudyID = num2str(patient.pt);
                end                %         X=dicomread(s);

                %         X=dicomread(s);
                %         cd(folder_output)
                %         cd(dicom_folder)
                %             cd(output_phase)
                %         dicomwrite(double(squeeze(X(:,:))),map,sprintf('image_phase_5_slice%d.dcm',slice),  info);
                output_file_tmp = fullfile(output_phase,sprintf('image_Phase_%02d_slice%d.dcm',phases(phase),slice) );
                dicomwrite(uint16(double(squeeze(img_dcm(:,:,slice)))),output_file_tmp,  info, 'CreateMode', 'Copy');
                
              
                
            end
        end

        
    end
    
    
    %%  dicomanon